package com.cbtx.module.base;

import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/6/10 6:15 PM
 * desc   :
 */
public class FileTools {
    private static final String TAG = "FileTools";


    public static boolean isFileExist(String filePath) {
        boolean result = false;
        File file = new File(filePath);
        if (file != null && file.exists() && file.isFile()) {
            result = true;
        }
        return result;
    }


    public static boolean isDirExist(String dirPath) {
        boolean result = false;
        File dir = new File(dirPath);
        if (dir != null && dir.exists() && dir.isDirectory()) {
            result = true;
        }
        return result;
    }

    public static String[] getFileNames(String dirPath) {
        String[] files = null;
        if (isDirExist(dirPath)) {
            File dir = new File(dirPath);
            files = dir.list();
        }
        return files;
    }

    public static File[] getFiles(String dirPath) {
        File[] files = null;
        if (isDirExist(dirPath)) {
            File dir = new File(dirPath);
            files = dir.listFiles();
        }
        return files;
    }


    public static String getContent(String file) {

        StringBuffer sb = new StringBuffer("");
        if (isFileExist(file)) {
            try {
                BufferedReader buf = new BufferedReader(new FileReader(file));
                String line = "";
                while ((line = buf.readLine()) != null) {
                    sb.append(line);
                }
                buf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * create file
     *
     * @param file path
     * @param file content
     */
    public static void createNewFile(String file, String content) {
        try {
            if (!isFileExist(file)) {
                File newFile = new File(file);
                newFile.createNewFile();
            }
            if (!TextUtils.isEmpty(content)) {
                write(file, content, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void creatDirectory(String path) {
        File dir = new File(path);
        Log.d(TAG, "creat dir " + path);
        if (!dir.exists() || !dir.isDirectory()) {
            if (dir.mkdirs()) {
                dir.setExecutable(true, false);
                dir.setReadable(true, false);
                dir.setWritable(true, false);
                Log.d(TAG, "create directory success---" + path);
            } else {
                Log.d(TAG, "create directory fail---" + path);
            }
        }
    }


    public static boolean updateFile(String filePath, String content) {
        boolean result = false;
        try {
            if (!isFileExist(filePath)) {
                Log.d(TAG, "file not exist---" + filePath);
            } else {
                write(filePath, content, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    protected static void write(String filename, String content,
                                boolean isAppend) {
        try {
            FileWriter fw = new FileWriter(filename, isAppend);
            fw.write(content);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static boolean delete(String filename) {
        boolean result = false;
        File file = new File(filename);
        if (file.exists()) {
            result = file.delete();
        } else {
            result = true;
        }
        return result;
    }


    public static void deleteFiles(String path) {
        File dir = new File(path);

        if (dir != null && dir.exists() && dir.isDirectory()) {
            String[] files = dir.list();
            if (files != null && files.length > 0) {
                for (String file : files) {
                    delete(path + File.separator + file);
                }
            }
        }
    }

    /**
     * move file
     *
     * @param srcFile
     * @param dirFile
     * @return
     */
    public static void mvFile(String srcFile, String dirFile) {

        String commond = "mv " + srcFile + " " + dirFile;
        doCommand(commond);
        if (changeMode(dirFile, 777) != 0) {
            File file = new File(dirFile);
            file.setExecutable(true, false);
            file.setReadable(true, false);
            file.setWritable(true, false);
        }
    }

    /** */
    /**
     * 文件重命�?
     *
     * @param path    文件目录
     * @param oldname 原来的文件名
     * @param newname 新文件名
     */
    public static void renameFile(String path, String oldname, String newname) {
        if (!oldname.equals(newname)) { // 新的文件名和以前文件名不同时,才有必要进行重命�?
            File oldfile = new File(path + "/" + oldname);
            File newfile = new File(path + "/" + newname);
            if (!oldfile.exists()) {
                return; // 重命名文件不存在
            }
            if (newfile.exists()) { // 若在该目录下已经有一个文件和新文件名相同，则不允许重命名
                System.out.println(newname + "已经存在�?");
            } else {
                oldfile.renameTo(newfile);
                newfile.setExecutable(true, false);
                newfile.setReadable(true, false);
                newfile.setWritable(true, false);
            }
        } else {
            System.out.println("新文件名和旧文件名相�?...");
        }
    }

    /**
     * change file mode---now using Runtime, no ProcessBuilder, because it is
     * failed.
     *
     * @param mode
     * @return
     */
    public static int changeMode(String file, int mode) {
        int status = -1;

        String commond = "chmod " + mode + " " + file;
        status = doCommand(commond);
        return status;
    }

    /**
     * execute instruction
     *
     * @param command
     * @return
     */
    protected static int doCommand(String command) {
        int status = -1;
        for (int i = 0; i < 10; i++) {
            try {
                Log.d(TAG, "set command --- " + command);
                Runtime runtime = Runtime.getRuntime();
                Process proc = runtime.exec(command);
                try {
                    status = proc.waitFor();
                } catch (InterruptedException e) {
                    Log.d(TAG, "set command failed--------------");
                    e.printStackTrace();
                }
                if (status == 0) {
                    Log.d(TAG, "set chmod succeed" + i);
                    break;
                } else {
                    status = -1;
                    Log.d(TAG, "set chmod failed.");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return status;
    }

    public static boolean copyFile(String oldPath, String newPath) {
        boolean flag = false;
        try {
            Log.i("Huan", "old path ==" + oldPath);
            Log.i("Huan", "new path ==" + newPath);
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {
                Log.i("Huan", "old path ==cunzai");
                InputStream inStream = new FileInputStream(oldPath);
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];

                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                flag = true;
            }
        } catch (Exception e) {
            Log.i("ad", "copy error");
            e.printStackTrace();
        }

        return flag;

    }

    public static String getFileMD5(String filePath) {
        String md5 = "";
        File file = new File(filePath);
        if (file.exists()) {
            MessageDigest messageDigest;
            try {
                messageDigest = MessageDigest.getInstance("MD5");
                InputStream in = new FileInputStream(file);
                byte[] cache = new byte[1024];
                int nRead = 0;
                while ((nRead = in.read(cache)) != -1) {
                    messageDigest.update(cache, 0, nRead);
                }
                in.close();
                byte[] data = messageDigest.digest();
                md5 = byteToHex(data);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                md5 = "";
            } catch (IOException e) {
                e.printStackTrace();
                Log.d(TAG, "IOException-----" + e.toString());
                md5 = "";
            }
        }
        return md5;
    }

    protected static String byteToHex(byte[] bytes) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        StringBuffer stringbuffer = new StringBuffer(2 * bytes.length);
        for (byte b : bytes) {
            char c0 = hexDigits[b >>> 4 & 0xf];
            char c1 = hexDigits[b & 0xf];
            stringbuffer.append(c0);
            stringbuffer.append(c1);
        }
        return stringbuffer.toString();
    }
}
